package logic

import (
	"context"
	"fmt"
	"user-rge/cache"
	"user-rge/model"
	"user-rge/pkg"

	"user-rge/userrpc/internal/svc"
	"user-rge/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user model.User
	model.DB.Debug().Where("tel=?", in.Tel).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该用户未注册，请前去注册")
	}
	if user.Password != pkg.Md5Str(in.Password) {
		return nil, fmt.Errorf("密码错误，请重新输入")
	}
	c, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Tel).Result()
	if in.Captcha != c {
		return nil, fmt.Errorf("图形验证码错误")
	}
	return &userrpc.LoginResponse{
		Id: int64(user.ID),
	}, nil
}
